var _ = require('lodash'),
    Q = require('q'),
    mongoose = require('mongoose'),
    BaseFun = require('../../../Base/server/controllers/Function'),
    entityCollection = require('../../../Base/server/controllers/EntityCollection'),
    BarcodeEnum = require('../../../Barcode/server/controllers/Enum.server.controller'),
    Transaction = require('../../../Base/server/controllers/Transaction'),
    BaseEnum = require('../../../Base/server/controllers/Enum'),
    workLocationController = require('../../../CBO/server/controllers/WorkLocation.server.controller');

// 搜集异常流水
// bindContext包含字段：Work、WorkName、WorkLacation、WorkLacationName、User
exports.collectProcessException = function (barcodeMasters, bindContext, exceptions) {
    var deferred = Q.defer();

    workLocationController.findById(
        bindContext.WorkLocation, { Department: 1 }, { path: 'Department', select: 'Name' }
    ).then(function (workLocationRecord) {
        if (!workLocationRecord) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询工位错误';
            newErr.message = '没有找到对应工位';
            deferred.reject(newErr);
            return;
        }
        var records = [];
        _.forEach(barcodeMasters, function (barcodeMaster) {
            _.forEach(exceptions, function (exception) {
                var exceptionType = exception.exceptionType,
                    missingOperations = exception.missingOperations;
                if ((exceptionType === BarcodeEnum.ExceptionType.DrainScard.Value ||
                    exceptionType === BarcodeEnum.ExceptionType.TimingScan.Value ) &&
                    missingOperations && missingOperations.length > 0
                ) {
                    _.forEach(missingOperations, function (operation) {
                        records.push({
                            _id: BaseFun.getObjectId(),
                    RowStatus: BaseEnum.RowStatus.Insert.Value,
                            CreatedBy: bindContext.User ? bindContext.User.Code : '',
                            Barcode: barcodeMaster.Barcode,
                            ItemMasterCode: barcodeMaster.ItemMasterCode,
                            ItemMasterName: barcodeMaster.ItemMasterName,
                            QCStatus: barcodeMaster.QCStatus,
                            DepartmentName: workLocationRecord.Department.Name,
                            WorkLocationName: bindContext.WorkLocationName,
                            WorkName: bindContext.WorkName,
                            ExceptionType: exceptionType,
                            MissingWorkName: operation.Work.Name,
                            IsRead: false,
                            DescSeg1: barcodeMaster.DescSeg1,
                            DescSeg2: barcodeMaster.DescSeg2
                        });
                    });
                } else {
                    records.push({
                        _id: BaseFun.getObjectId(),
                RowStatus: BaseEnum.RowStatus.Insert.Value,
                        CreatedBy: bindContext.User ? bindContext.User.Code : '',
                        Barcode: barcodeMaster.Barcode,
                        ItemMasterCode: barcodeMaster.ItemMasterCode,
                        ItemMasterName: barcodeMaster.ItemMasterName,
                        QCStatus: barcodeMaster.QCStatus,
                        DepartmentName: workLocationRecord.Department.Name,
                        WorkLocationName: bindContext.WorkLocationName,
                        WorkName: bindContext.WorkName,
                        ExceptionType: exceptionType,
                        IsRead: false,
                        DescSeg1: barcodeMaster.DescSeg1,
                        DescSeg2: barcodeMaster.DescSeg2
                    });
                }
            });
        });
        deferred.resolve({ EntityName: 'ProcessException', Records: records });
    }, function (err) {
        deferred.reject(err);
    });

    return deferred.promise;
};